<template>
  <div style="padding: 10px">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="addGoose">新增</el-button>
      <el-popconfirm style="margin: 10px 10px" title="确定删除吗？" @onConfirm="selectDelete">
        <template #reference>
          <el-button type="primary">删除选中</el-button>
        </template>
      </el-popconfirm>
      <el-button type="primary" @click="exportExcel">导出Excel</el-button>
    </div>
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入关键字查询" style="width: 40%;background-color: #fff">
        <el-select slot="prepend" v-model="select" placeholder="请选择" style="width: 120px">
          <el-option label="产品名称" value="gooseName" />
          <el-option label="售价" value="price" />
          <el-option label="成本" value="cost" />
          <el-option label="产品ID" value="gooseID" />
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="inquire" />
      </el-input>
    </div>
    <!--    表格区域-->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
      :header-cell-style="headClass"
      :cell-style="rowClass"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="序号"
        type="index"
        :index="indexMethod"
        sortable
      />
      <el-table-column
        prop="gooseId"
        label="产品ID"
        sortable
      />
      <el-table-column
        prop="gooseName"
        label="产品名称"
      />
      <el-table-column
        prop="standard"
        label="规格"
      />
      <el-table-column
        prop="price"
        label="售价"
        sortable
      />
      <el-table-column
        prop="cost"
        label="成本"
        sortable
      />
      <el-table-column
        label="图片"
      >
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.photoUrl"
            :preview-src-list="[scope.row.photoUrl]"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="createDate"
        label="创造日期"
        :formatter="formatDate"
        sortable
      />
      <el-table-column label="操作" width="140">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @onConfirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button style="margin-left: 5px" size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <div style="margin: 10px 0">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--    增加商品弹窗-->
    <el-dialog
      title="添加商品"
      :visible.sync="addGooseVisible"
      width="30%"
      center
      :show-close="false"
    >
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item
          label="产品名称"
          prop="gooseName"
          :rules="{required: true, message: '产品名称不能为空', trigger: 'blur'}"
        >
          <el-input v-model="form.gooseName" style="width: 80%" />
        </el-form-item>
        <el-form-item
          label="规格"
          prop="standard"
          :rules="{required: true, message: '规格不能为空', trigger: 'blur'}"
        >
          <el-input v-model="form.standard" style="width: 80%" placeholder="5个/盒" />
        </el-form-item>
        <el-form-item
          label="售价"
          prop="price"
          :rules="{required: true, message: '售价不能为空', trigger: 'blur'}"
        >
          <el-input v-model="form.price" type="number" style="width: 70%" />
          元
        </el-form-item>
        <el-form-item
          label="成本"
          prop="cost"
          :rules="{required: true, message: '成本不能为空', trigger: 'blur'}"
        >
          <el-input v-model="form.cost" type="number" style="width: 70%" />
          元
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PBG"
            :on-success="filesUploadSuccess"
            :on-error="filesUploadError"
            :on-remove="fileRemove"
            :action="uploadPhotoUrl"
            :headers="myHeaders"
            :file-list="fileList"
          >
            <el-button type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片文件文件，且不超过5MB</div>
          </el-upload>
          <el-image
            v-show="fileList.length == 0 ? false:true"
            style="width: 50px; height: 50px"
            :src="form.photoUrl"
            :preview-src-list="[form.photoUrl]"
          />
        </el-form-item>
        <el-form-item label="创造日期">
          <el-date-picker
            v-model="form.createDate"
            style="width: 80%"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :editable="false"
          >
            >
          </el-date-picker>
        </el-form-item>
        <div style="margin-top: 50px;text-align: center">
          <el-button style="margin-right: 20px" size="big" @click="cancel">取 消</el-button>
          <el-button style="margin-left: 20px" size="big" type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>

import { addGoose, deleteById, deleteFiles, selectGoose, update, uploadPhotoUrl } from '@/api/goose'
import { Message } from '_element-ui@2.13.2@element-ui'
import { getToken } from '@/utils/auth'
import { formatTimer, parseTime } from '@/utils'

export default {
  name: 'Goods',
  data() {
    return {
      // 新增及修改加载小图
      fileList: [],
      // 由于未使用request函数需要手动添加头部token
      myHeaders: { 'X-Token': getToken() },
      // 上传图片URL
      uploadPhotoUrl: uploadPhotoUrl,
      // 添加商品表格
      form: {},
      // 添加商品弹窗,默认关闭
      addGooseVisible: false,
      // 每页查看数量
      pageSizes: [10, 20, 50, 200],
      // 每页显示数量
      pageSize: 10,
      // 总数量
      total: 0,
      // 当前页
      currentPage: 1,
      // 查询输入框
      search: '',
      // 查询选择项目
      select: 'gooseName',
      // 表格数据
      tableData: [],
      // 选中数据
      multipleSelection: []
    }
  },
  mounted() {
    // 默认加载根据名称查询
    this.selectPage(this.currentPage, this.pageSize)
  },
  methods: {
    // 导出Excel 工具
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 导出Excel
    exportExcel() {
      if (this.tableData.length > 0) {
        // 格式化日期
        for (const g of this.tableData) {
          g.createDate = formatTimer(g.createDate)
        }
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['产品ID', '产品名称', '规格', '售价', '成本', '创建日期']
          const filterVal = ['gooseId', 'gooseName', 'standard', 'price', 'cost', 'createDate']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader, // 表头 必填
            data, // 具体数据 必填
            filename: '商品数据', // 非必填
            autoWidth: true, // 非必填
            bookType: 'xlsx' // 非必填
          })
        })
      }
    },
    // 页码跟序号处理 工具
    indexMethod(index) {
      const currentPage = this.currentPage // 当前页码
      const pageSize = this.pageSize // 每页条数
      return index + 1 + (currentPage - 1) * pageSize // 返回表格序号
    },
    // 日期处理 工具
    formatDate(row, column) {
      // 获取单元格数据
      const data = row[column.property]
      if (data == null) {
        return null
      }
      const dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    // 点击查询
    inquire() {
      // 调用查询方法
      this.selectPage(this.currentPage, this.pageSize)
    },
    // 查询代码抽取 工具
    selectPage(currentPage, pageSize) {
      new Promise((resolve, reject) => {
        // 查询求情
        selectGoose(currentPage, pageSize, this.search, this.select).then(res => {
          // 赋值给页面渲染
          this.tableData = res.data.records
          // 赋值总数
          this.total = res.data.total
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 图片取消钩子
    fileRemove() {
      deleteFiles(this.form).then(res => {
        if (res.code === 20000) {
          Message({
            message: '取消成功!',
            type: 'success',
            duration: 3 * 1000
          })
        }
        this.form.photoUrl = null
        this.fileList = []
      })
    },
    // 新增取消
    cancel() {
      this.addGooseVisible = false
      // 清空上传组件数据
      this.$refs['upload'].clearFiles()
      if (this.form.photoUrl != null && this.form.id == null) {
        // 发送删除接口
        this.fileRemove()
      }
      this.form = {}
    },
    // 文件上传失败钩子
    filesUploadError(err) {
      if (JSON.parse(err.message).code === 502) {
        Message({
          message: '文件上传过大,请不要超过5MB!',
          type: 'error',
          duration: 5 * 1000
        })
      }
      this.fileList = []
    },
    // 文件上传成功钩子
    filesUploadSuccess(res) {
      this.form.photoUrl = res.data
      this.fileList = [{ 'name': this.form.gooseName, 'url': this.form.photoUrl }]
    },
    // 提交
    submitForm(form) {
      if (this.form.id) {
        // 修改
        new Promise((resolve, reject) => {
          update(this.form).then(response => {
            if (response.code === 20000) {
              Message({
                message: '修改成功!',
                type: 'success',
                duration: 3 * 1000
              })
            }
            // 关闭新增窗口
            this.addGooseVisible = false
            // 刷新数据页面,否则乐观锁会锁死
            this.selectPage(this.currentPage, this.pageSize)
            // 清空上传组件数据
            this.form = {}
            this.fileList = []
            this.$refs['upload'].clearFiles()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      } else {
        // 新增
        this.$refs[form].validate((valid) => {
          if (valid) {
            new Promise((resolve, reject) => {
              addGoose(this.form).then(response => {
                if (response.code === 20000) {
                  Message({
                    message: '添加成功!',
                    type: 'success',
                    duration: 3 * 1000
                  })
                }
                // 刷新数据页面
                this.selectPage(this.currentPage, this.pageSize)
                // 关闭新增窗口
                this.addGooseVisible = false
                // 清空上传组件数据
                this.form = {}
                this.fileList = []
                this.$refs['upload'].clearFiles()
                resolve()
              }).catch(error => {
                reject(error)
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    // 点击新增按钮
    addGoose() {
      // 获取今天时间到日期框
      this.form.createDate = new Date()
      // 打开新增视图
      this.addGooseVisible = true
    },
    // 改变每页显示条数触发
    handleSizeChange(val) {
      this.pageSize = val
      this.selectPage(this.currentPage, val)
    },
    // 改变当前页码触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.selectPage(val, this.pageSize)
    },
    // 表头居中显示
    headClass() {
      return 'text-align:center'
    },
    // 表格数据居中显示
    rowClass() {
      return 'text-align:center'
    },
    // 全选或全不选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 编辑按钮
    handleEdit(row) {
      // 打开新增窗口,改变为编辑
      this.addGooseVisible = true
      // 赋值编辑窗口
      this.form = row
      this.fileList = [{ 'name': this.form.gooseName, 'url': this.form.photoUrl }]
    },
    // 删除按钮
    handleDelete(id) {
      new Promise((resolve, reject) => {
        deleteById(id).then(response => {
          if (response.code === 20000) {
            Message({
              message: '删除成功!',
              type: 'success',
              duration: 3 * 1000
            })
          }
          // 刷新数据页面
          this.selectPage(this.currentPage, this.pageSize)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 选中删除
    selectDelete() {
      for (const multipleSelection of this.multipleSelection) {
        this.handleDelete(multipleSelection.id)
      }
    }
  }
}
</script>

<style scoped>
</style>
